// 分页功能
let offset = 1;
let allPages;
var last = document.querySelector(".last");
var next = document.querySelector(".next");
let keywords = "";
function page(offset, allPages) {
  getCourse(offset, allPages);
  if (offset == 1) {
    last.setAttribute("disabled", true);
  }
  if (offset >= allPages) {
    offset = allPages;
    next.setAttribute("disabled", true);
  }
  if (offset < allPages) {
    next.removeAttribute("disabled");
  }
  next.onclick = function () {
    offset++;
    checkAll.checked = false;
    if (offset >= 1) {
      last.removeAttribute("disabled");
    }
    if (offset >= allPages) {
      offset = allPages;
      next.setAttribute("disabled", true);
    }
    getCourse(offset, allPages);
  };
  last.onclick = function () {
    checkAll.checked = false;
    offset--;
    getCourse(offset, allPages);
    if (offset <= 1) {
      last.setAttribute("disabled", true);
      offset = 1;
    }
    if (offset < allPages && offset >= 1) {
      next.removeAttribute("disabled");
    }
  };
}
// 渲染当前页的数据
function getCourse(offset = 1, allPages, keywords = "") {
  checkAll.checked = false; // 获取数据

  $.ajax({
    url: `http://110.40.139.172:43120/course/getAllcourse`,
    method: "get",
    data: {
      offset,
      keywords,
    },
    headers: {
      token: localStorage.getItem("token"),
    },
    success: function (result) {
      var arr = result.userInfo;

      allPages = result.allPages;
      var select = document.querySelector("#add-category");
      var tbody = document.querySelector("#tb");

      if (arr.length == 0 && keywords != "") {
        var table = document.getElementById("stu");
        let search = document.getElementsByClassName("search")[0];
        let inputsValue = search.getElementsByTagName("input")[0];

        alertErr("该数据不存在");
        click = false;
        inputsValue.value = "";
        getArr();
        return;
      }
      tbody.innerHTML = " ";
      if (arr.length != 0 && result.code == 0) {
        for (var i = 0; i < arr.length; i++) {
          let cvalue = arr[i].category;
          let mvalue = arr[i].assessmentMethod;
          let categoryText = document.querySelector(
            `#add-category option[value="${cvalue}"]`
          ).text;
          let methodText = document.querySelector(
            `#Method option[value="${mvalue}"]`
          ).text;
          tbody.innerHTML =
            tbody.innerHTML +
            `<tr>
          <td><input type="checkbox" class="check" name="items" val=${
            arr[i].id
          }  off=${result.offset}></td>
        <td data-id=${arr[i].id}>${i + 1 + (offset - 1) * 10}</td>
        <td>${arr[i].courseName}</td>
        <td>${categoryText}</td>
        <td>${arr[i].attentClassTime}</td>
        <td>${arr[i].classRoom}</td>
        <td>${arr[i].creditHour}</td>
        <td>${methodText}</td>
        <td>
          <button type="button" class="remove" onclick="delRow(this)" data-id=${
            arr[i].id
          }>
            <i class="iconfont">&#xe61c;</i>
          </button>
          <button
            type="button"
            class="edit"
            onclick="updateRow(this)"
          >
            <i class="iconfont">&#xe8cf;</i>
          </button>
        </td>
      </tr>`;
        }
      } else if (arr.length == 0 && offset > 1) {
        offset--;
        page(offset, allPages);
      }
      ischeckAll();
      isCheck();
      background();
      document.querySelector(".total-count").innerHTML = `共${allPages}页`;
      document.querySelector(".nowpage").innerHTML = `第${offset}页`;
      if (offset == 1) {
        last.setAttribute("disabled", true);
      }
      if (offset >= allPages) {
        offset = allPages;
        next.setAttribute("disabled", true);
        return;
      }
      if (offset < allPages) {
        next.removeAttribute("disabled");
      }
    },
  });
}

function getArr() {
  $.ajax({
    url: `http://110.40.139.172:43120/course/getAllcourse`,
    method: "get",
    headers: {
      token: localStorage.getItem("token"),
    },
    success: function (result) {
      var count = result.count;
      var allPages = result.allPages;
      var offset = result.offset;
      page(offset, allPages);
    },
  });
}

getArr();
// 退出页面
var backBtn = document.querySelector(".backBtn");
backBtn.onclick = function () {
  confirm("确定退出登录吗？")
    .then(function () {
      localStorage.removeItem("token");
      window.location.replace("login.html");
    })
    .catch(function () {});
};

// 添加模块
var addBtn = document.getElementsByClassName("addBtn")[0];
addBtn.onclick = function add() {
  let category = document.getElementById("add-category");
  let assessmentMethod = document.getElementById("Method");
  let trs = document.getElementsByTagName("tr");
  let mask = document.querySelector(".mask");
  let cancel = document.querySelector(".cancel");
  let addinfo = document.getElementById("addinfo");
  let addTo = document.getElementsByClassName("add")[0];
  let inputValue = addinfo.getElementsByTagName("input");
  let check = document.querySelectorAll(".check")[0];
  let offset = check.getAttribute("off");
  var search = document.getElementsByClassName("search")[0];
  var inputsValue = search.getElementsByTagName("input")[0];
  inputsValue.value = "";

  //清除之前输入框的内容
  for (var i = 0; i < 4; i++) {
    inputValue[i].value = "";
  }
  category.options[0].selected = true;
  assessmentMethod.options[0].selected = true;
  cancel.onclick = function () {
    mask.style.display = "none";
  };
  mask.onclick = function (e) {
    if (e.target == mask) mask.style.display = "none";
  };
  mask.style.display = "flex";
  addTo.onclick = function () {
    let category = document.getElementById("add-category");
    let categoryIndex = category.selectedIndex;
    let assessmentMethod = document.getElementById("Method");
    let courseName = setText(inputValue[0].value);
    let attentClassTime = setText(inputValue[1].value);
    let classRoom = setText(inputValue[2].value);
    let creditHour = setText(inputValue[3].value);
    let categoryText = category.options[categoryIndex].text;
    let assessmentMethodIndex = assessmentMethod.selectedIndex;
    let assessmentMethodText =
      assessmentMethod.options[assessmentMethodIndex].text;
    if (
      courseName == "" ||
      attentClassTime == "" ||
      classRoom == "" ||
      creditHour == ""
    ) {
      alertErr("输入数据不能为空");
      return;
    }
    if (
      courseName < 0 ||
      attentClassTime < 0 ||
      classRoom < 0 ||
      creditHour < 0
    ) {
      alertErr("输入数据不能为负");
      return;
    }

    $.ajax({
      url: "http://110.40.139.172:43120/course/add",
      method: "post",
      data: {
        courseName,
        category: category.value,
        attentClassTime,
        classRoom,
        creditHour,
        assessmentMethod: assessmentMethod.value,
      },
      headers: {
        token: localStorage.getItem("token"),
      },
      success: function (result) {
        var arr = result.courseInfo;
        localStorage.getItem("token");
        if (result.code == 0) {
          mask.style.display = "none";
          alertSuccess("添加成功");
          page(offset, allPages);
        } else alertErr(result.message);
      },
      error: function (error) {
        console.log(error);
      },
    });
  };
};
// 删除功能
function delRow(btn) {
  // 获取table对象
  var table = document.getElementById("stu");
  // 获取要删除的行对象(按钮的父对象是td td的父对象是tr)
  var tr = btn.parentNode.parentNode;
  let tds = tr.getElementsByTagName("td");
  var id = btn.dataset.id;

  let check = document.querySelectorAll(".check")[0];
  var search = document.getElementsByClassName("search")[0];
  var inputValue = search.getElementsByTagName("input")[0];
  var keywords = setText(inputValue.value);

  confirm("是否删除？(一旦删除无法恢复)")
    .then(function () {
      $.ajax({
        url: `http://124.222.153.56:43120/course/getAllcourse`,
        method: "get",
        headers: {
          token: localStorage.getItem("token"),
        },
        data: {
          keywords: keywords,
        },
        success: function (result) {
          let arr = result.userInfo;
          let allPages = result.allPages;
          let offset = check.getAttribute("off");

          $.ajax({
            url: `http://110.40.139.172:43120/course/del?ids=${id}`,
            type: "delete",
            headers: {
              token: localStorage.getItem("token"),
            },
            success: function (result) {
              if (click == true) {
                getCourse(offset, allPages, keywords);
              } else if (keywords == "" && click == false) {
                alertSuccess("删除成功");
                getCourse(offset, allPages);
              }
            },
            error: function (error) {
              alertErr("删除失败");
            },
          });
        },
      });
    })
    .catch(function () {});
}
// 查询模块
let click = false;
var searchBtn = document.getElementById("search");
searchBtn.onclick = function research() {
  checkAll.checked = false;
  //获取文本框内容
  var search = document.getElementsByClassName("search")[0];
  var inputValue = search.getElementsByTagName("input")[0];
  var keywords = setText(inputValue.value);
  // 获取表格中的列
  var trs = document.getElementsByTagName("tr");
  var len = trs.length;
  if (keywords == "") {
    return alertErr("请输入数据");
  }
  click = true;
  getCourse(offset, allPages, keywords);
};

// 让背景框随列表长度的改变而改变
function background() {
  var trs = document.getElementsByTagName("tr");
  var info = document.getElementsByClassName("info")[0];
  var length = trs.length;
  info.style.height = 200 + length * 30 + "px";
  if (200 + length * 30 < 680) info.style.height = "680px";
}
background();
// 查询后的刷新功能
var fresh = document.querySelector(".fresh");
fresh.onclick = function refresh() {
  click = true;
  let search = document.getElementsByClassName("search")[0];
  let inputValue = search.getElementsByTagName("input")[0];
  inputValue.value = "";
  alertSuccess("刷新成功");
  getArr();
};

// 修改功能
function updateRow(obj) {
  var thisTr = obj.parentNode.parentNode;
  var tds = thisTr.getElementsByTagName("td");
  var id = tds[1].dataset.id;
  var editorMask = document.querySelector(".mask-editor");
  var changeInfo = document.getElementById("changeinfo");
  var inputs = changeInfo.getElementsByTagName("input");
  // 获取两个下拉框
  var category = document.getElementById("editor-category");
  var editorMethod = document.getElementById("editor-method");
  let cancel = editorMask.querySelector(".cancel");
  editorMask.style.display = "flex";
  cancel.onclick = function () {
    editorMask.style.display = "none";
  };
  editorMask.onclick = function (e) {
    if (e.target == editorMask) editorMask.style.display = "none";
  };
  // 回显
  inputs[0].value = tds[2].innerHTML;
  inputs[1].value = tds[4].innerHTML;
  inputs[2].value = tds[5].innerHTML;
  inputs[3].value = tds[6].innerHTML;
  //获取表格的内容，遍历所有的下拉框的内容（通过索引），如果有匹配的
  for (var i = 0; i < category.length; i++) {
    if (tds[3].innerHTML == category.options[i].text) {
      category.options[i].selected = true;
    }
  }
  for (var j = 0; j < editorMethod.length; j++) {
    if (tds[7].innerHTML == editorMethod.options[j].text) {
      editorMethod.options[j].selected = true;
    }
  }
  var editorBtn = document.querySelector(".editor");
  editorBtn.onclick = function (obj) {
    var inputs = changeInfo.getElementsByTagName("input");
    var courseName = setText(inputs[0].value);
    var attentClassTime = setText(inputs[1].value);
    var classRoom = setText(inputs[2].value);
    var creditHour = setText(inputs[3].value);
    var categoryIndex = category.selectedIndex;
    var cText = category.options[categoryIndex].text;
    var aIndex = editorMethod.selectedIndex;
    var aText = editorMethod.options[aIndex].text;

    if (
      courseName == "" ||
      attentClassTime == "" ||
      classRoom == "" ||
      creditHour == ""
    ) {
      alertErr("输入数据不能为空");
      return;
    }
    if (
      courseName < 0 ||
      attentClassTime < 0 ||
      classRoom < 0 ||
      creditHour < 0
    ) {
      alertErr("输入数据不能为负");
      return;
    }
    $.ajax({
      url: "http://110.40.139.172:43120/course/changeInfo",
      type: "post",
      data: {
        id,
        courseName,
        category: categoryIndex + 1,
        attentClassTime,
        classRoom,
        creditHour,
        assessmentMethod: aIndex,
      },
      headers: {
        token: localStorage.getItem("token"),
      },
      success: function (result) {
        if (result.code == 0) {
          editorMask.style.display = "none";
          tds[2].innerHTML = courseName;
          tds[3].innerHTML = cText;
          tds[4].innerHTML = attentClassTime;
          tds[5].innerHTML = classRoom;
          tds[6].innerHTML = creditHour;
          tds[7].innerHTML = aText;
          return alertSuccess("修改成功");
        } else {
          return alertErr(result.message);
        }
      },
      error: function (error) {
        return alertErr("修改失败");
      },
    });
  };
}

// 全选功能
function ischeckAll() {
  let checkAll = document.querySelector(".checkAll");
  let checks = document.querySelectorAll(".check");
  checkAll.onclick = function () {
    for (var i = 0; i < checks.length; i++) {
      checks[i].checked = checkAll.checked;
    }
  };
  if (checkAll.checked == true) {
    for (var i = 0; i < checks.length; i++) {
      checks[i].checked = checkAll.checked;
    }
  }
}

// 删除选中的;
var checkBtn = document.querySelector(".checkBtn");
checkBtn.onclick = function () {
  var checkeds = document.querySelectorAll(`.check:checked`);
  if (checkeds.length == 0) {
    return alertErr("请至少选择一项进行删除");
  }
  let offset = checkeds[0].getAttribute("off");
  var ids = [];
  for (let i = 0; i < checkeds.length; i++) {
    let val = checkeds[i].getAttribute("val");
    ids.push(val);
  }
  var search = document.getElementsByClassName("search")[0];
  var inputValue = search.getElementsByTagName("input")[0];
  var keywords = setText(inputValue.value);
  confirm("是否删除选中的数据（一旦删除无法恢复）")
    .then(function () {
      $.ajax({
        url: `http://110.40.139.172:43120/course/del?ids= ${ids}`,
        type: "delete",
        headers: {
          token: localStorage.getItem("token"),
        },
        success: function (result) {
          if (click == true) {
            getCourse(offset, allPages, keywords);
          } else if (keywords == "" && click == false) {
            alertSuccess("删除成功");
            getCourse(offset, allPages);
          }
        },
        error: function (error) {
          alertErr("删除失败");
        },
      });
    })
    .catch(function () {});
};

// 如果多选框全选中，则全选框应该选中，如果多选框没都选中，则全选框不选中
// 为多选框分别绑定单击响应函数
let items = document.getElementsByName("items");
let checkAll = document.querySelector(".checkAll");
function isCheck() {
  for (let i = 0; i < items.length; i++) {
    items[i].onclick = function () {
      // 将全选框设置为选中状态
      checkAll.checked = true;
      // 点击一个多选框后还需要判断所有多选框的状态
      for (let j = 0; j < items.length; j++) {
        if (!items[j].checked) {
          //一旦进入判断语句，则证明有未选中的多选框
          checkAll.checked = false;
        }
      }
    };
  }
}

// 重写confirm
function confirm(msg) {
  let sure = document.querySelector(".c-sure");
  let cancel = document.querySelector(".c-cancel");
  let conCancel = document.querySelector(".confirm-cancel");
  let mask = document.querySelector(".confirm-mask");
  let content = document.querySelector(".confirm-content");
  let span = content.querySelector("span");
  span.innerHTML = msg;
  mask.style.display = "flex";

  let cPromise = new Promise(function (resolve, reject) {
    sure.onclick = function () {
      mask.style.display = "none";
      resolve();
    };
    cancel.onclick = function () {
      mask.style.display = "none";
      reject();
    };
    conCancel.onclick = function () {
      mask.style.display = "none";
      reject();
    };
  });
  return cPromise;
}

// 重写alert
const alert = document.querySelector(".alert");
let msgalert = alert.querySelector("span");
function alertSuccess(msg) {
  alert.innerHTML = `<i class="iconfont">&#xe602;</i><span>${msg}</span>`;
  msgalert.innerHTML = msg;
  alert.classList.add("success");
  alert.classList.add("show");
  setTimeout(function () {
    alert.classList.remove("show");
    alert.classList.remove("success");
  }, 2000);
}
function alertErr(msg) {
  alert.innerHTML = `<i class="iconfont">&#xe604;</i><span>${msg}</span>`;
  alert.classList.add("err");
  alert.classList.add("show");
  setTimeout(function () {
    alert.classList.remove("show");
    alert.classList.remove("err");
  }, 2000);
}

// 正则
function setText(val) {
  let msg = val.replace(/</g, "&lt;").replace(/>/g, "&gt;"); //执行替换成空字符
  msg = msg.replace(/\s/g, ""); //去掉所有的空格（中文空格、英文空格都会被替换）
  //去掉所有的换行符
  return msg; //获文本文字内容的前100个字符
}

if (localStorage.getItem("token") == null) {
  window.location.replace("../login.html");
}
